package com.jcxy.service.impl;

import com.jcxy.mapper.RoleMapper;
import com.jcxy.pojo.Menu;
import com.jcxy.pojo.Role;
import com.jcxy.service.RoleService;
import com.jcxy.util.PageBean;
import com.jcxy.util.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageBean queryListByPage(Map dto, Integer page, Integer limit) {

        Integer count = roleMapper.queryRoleCount(dto);
        PageBean pageBean = new PageBean(page, limit);
        dto.put("pageIndex",pageBean.getPageIndex());
        dto.put("limit",pageBean.getLimit());
        List<Role> roleList = roleMapper.queryRole(dto);

        pageBean.setResponseData(count,roleList);

        return pageBean;
    }

    @Override
    @Transactional
    public void deleteRoleById(Integer role_id) throws Exception {

        //删除角色的权利
        roleMapper.deleteRolePowerByRoleId(role_id);
        //删除角色
        int count = roleMapper.deleteRoleById(role_id);
        //删除成功条数大于1，抛出异常，事务回滚
        if (count > 1){
            throw new Exception("删除异常");
        }
    }

    @Override
    public Role queryRoleById(Map dto) {

        return roleMapper.queryRole(dto).get(0);
    }

    @Override
    @Transactional
    public void updateRole(Map dto) throws Exception {

        int count = roleMapper.updateRole(dto);

        if (count > 1){
            throw new Exception("更新异常！");
        }
    }

    @Override
    @Transactional
    public int addRole(Role role) throws Exception {

        //插入角色
        int count = roleMapper.insertRole(role);

        //查询所用菜单id
        List<Integer> menuIds = roleMapper.queryAllMenuId();
        Map dto = new HashMap();
        dto.put("role_id",role.getRole_id());
        //为角色添加权利
        for (Integer id : menuIds){
            dto.put("menu_id",id);
            roleMapper.insertRolePower(dto);
        }
        return count;
    }

    @Override
    public List<Menu> queryMenuList(Integer role_id) {

        return roleMapper.queryAllMenuAndPowerById(role_id);
    }

    @Override
    @Transactional
    public void updateRolePower(Map dto) throws Exception {

        int count = roleMapper.updateRolePower(dto);

        if(count > 1){
            throw new Exception("修改权限异常！");
        }

    }
}
